import { HttpResponse, IHttpResponse } from "./http-response"
export class Net {

  constructor(config?: IData) { }

  async request(url: string, config: IParams): Promise<IHttpResponse> {
    config.method = config.method ? config.method.toUpperCase() : undefined
    return new Promise<IHttpResponse>((resolve, reject) => {
      uni.request({
        url,
        ...config,
        dataType: 'json',
        // #ifndef MP-WEIXIN
        responseType: 'json',
        // #endif
        // 响应成功
        success(res) {
          resolve(
            new HttpResponse(res.data || undefined, res.statusCode, res.errMsg)
          )
        },
        // 响应失败
        fail(err) {
          reject(new HttpResponse(undefined, 408, err.errMsg))
        },
      })
    })
  }

  async post(
    url: string,
    data: IData,
    params: IParams = {},
    header: IData = {},
  ): Promise<IHttpResponse> {
    const response = await this.request(url, { method: 'post', data, header })
    return response
  }

  async get(
    url: string,
    params: IParams = {},
    header: IData = {},
    config: IParams = {},
  ): Promise<IHttpResponse> {
    const response = await this.request(url, {
      ...config,
      header,
      method: 'get'
    })
    return response
  }

  async delete(
    url: string,
    params: IParams = {},
    header: IData = {},
  ): Promise<IHttpResponse> {
    const response = await this.request(url, { method: 'delete', header })
    return response
  }

  async put(
    url: string,
    data: IData,
    params: IParams = {},
    header: IData = {},
  ): Promise<IHttpResponse> {
    const response = await this.request(url, { method: 'put', data, header })
    return response
  }

  async getModel(
    url: string,
    header: IData = {},
  ): Promise<IHttpResponse> {
    const response = await this.request(url, {
      header,
    });
    return response;
  }
}